package doc2db.interfaces.mainWindow;

import doc2db.Keey;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.DecimalFormat;
import javax.swing.AbstractAction;
import javax.swing.Box;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JProgressBar;

/**
 *
 * @author yura
 */
public class VMemory extends JPanel{
    public static final int MEGABYTE = (int) Math.pow(1024, 2);
    private final JProgressBar jProgressBar1 = new JProgressBar(0, 100);
    private final JProgressBar jProgressBar2 = new JProgressBar(0, 100);
    final Color[] gradient = {
        Color.WHITE, Color.GREEN.brighter(), Color.GREEN, Color.GREEN.darker(),
        Color.YELLOW.brighter(), Color.YELLOW, Color.YELLOW.darker(), Color.ORANGE,
        Color.ORANGE.darker(), Color.RED.brighter(), Color.RED
    };
    protected int refreshRate = 1;

    public VMemory() {
        super(new BorderLayout());
        jProgressBar1.setStringPainted(true);
        jProgressBar2.setStringPainted(true);
        Dimension d = new Dimension(140, 16);
        jProgressBar1.setSize(d);
        jProgressBar1.setPreferredSize(d);
        jProgressBar1.setMinimumSize(d);
        jProgressBar1.setMaximumSize(d);
        jProgressBar2.setSize(d);
        jProgressBar2.setPreferredSize(d);
        jProgressBar2.setMinimumSize(d);
        jProgressBar2.setMaximumSize(d);
        Box b = Box.createVerticalBox();
        b.add(jProgressBar1);
        b.add(Box.createHorizontalStrut(2));
        b.add(jProgressBar2);
        add(b, BorderLayout.CENTER);
        //setOrientation(SwingConstants.HORIZONTAL);
        setSize(150, 34);
        this.action();
        start();
    }

    public void action(){
        MouseListener m = new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) {
                    JPopupMenu m = new JPopupMenu();
                    JMenuItem select = new JMenuItem(new AbstractAction("зачистить") {
                        @Override
                        public void actionPerformed(ActionEvent e) {
                            System.gc();
                            System.out.println("Runs the garbage collector.");
                        }
                    });
                    m.add(select);
                    m.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        };
        jProgressBar1.addMouseListener(m);
        jProgressBar2.addMouseListener(m);
        //addMouseListener(m);
    }
    
    public void start() {
        new Thread() {
            @Override
            public void run() {
                setPriority(MIN_PRIORITY);
                Runtime run = Runtime.getRuntime();
                long max = run.maxMemory(), tot, free;
                while (true) {
                    if (!Keey.debug){//isDisplayable()) {
                        try {
                            sleep(1000);
                        } catch (InterruptedException ex) {}
                        continue;
                    }
                    try {
                        tot = run.totalMemory();
                        free = run.freeMemory();
                        prog(jProgressBar1, gradient, free, tot, tot, "<%>% of total memory is being used.");
                        prog(jProgressBar2, gradient, free, tot, max, "<%>% of maximum memory is being used.");
                        switch (refreshRate) {
                            case 1:
                                sleep(1000);
                                break;
                            case 10:
                                sleep(100);
                                break;
                            default:
                                Thread.yield();
                        }
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        setVisible(false);
                        break;
                    }
                }
            }
        }.start();
    }

    public static String memoryFormatM(double memory) {
        DecimalFormat f = new DecimalFormat(".00");
        String m = f.format(memory / MEGABYTE);
        return m;//.concat(" M");
    }

    public static void prog(JProgressBar p, Color[] gradient, double freeMem,
            double totMem, double maxMem, String tooltip) {
        double used = totMem - freeMem;
        if (totMem != maxMem) {
            double free = maxMem - used;
            used = maxMem - free;
        }
        int percent = (int) percentOf(used, maxMem);
        int p10 = (percent / 10) + 1;
        p.setForeground(gradient[p10]);
        p.setValue(percent);
        tooltip = tooltip.replaceAll("<%>", String.valueOf(percent));
        double usedMem = maxMem * ((double) percent / 100);
        tooltip += " [" + memoryFormatM(usedMem) + "/" + memoryFormatM(maxMem) +  " M]";
        p.setToolTipText(tooltip);
    }
    
    public static double percentOf(double dividend, double divisor) {
        return (dividend / divisor) * 100;
    }
}
